package com.demo.zipdemo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ZipUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipOutputStream;

public class zipDemo {
    /**
     * 方法说明:    将excel文件集合放到zip压缩包里面，输出后缀为zip的压缩文件，指定临时文件的路径
     * @param zipPath           压缩包路径
     * @param excelFileList     excel文件集合
     * @return java.io.File
     * @version v1.0
     * @author 梁阿龙[liangalong@fescotech.com]
     * @date 2022-04-08 13:47
     */
    private File packageToZip(String zipPath, List<File> excelFileList) {
        File zipFile = new File(zipPath + UUID.randomUUID() + ".zip");

        if (CollectionUtil.isNotEmpty(excelFileList)) {
            FileOutputStream fos = null;
            ZipOutputStream zos = null;
            try {
                fos = new FileOutputStream(zipFile);
                zos = new ZipOutputStream(new BufferedOutputStream(fos));
                File[] files = new File[excelFileList.size()];
                excelFileList.toArray(files);
                ZipUtil.zip(zos, true, null, files);
            } catch
            (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert fos != null;
                    assert zos != null;
                    zos.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return zipFile;
    }
}
